//#define USE_LOCAL_HTML  // 必须在文件顶部定义，且仅对该文件有效
using CefSharp.WinForms;
using CefSharp;
using DidaManager.Log;
using System.Windows.Forms;
using DidaManager.Handlers;
using LiteDb;
using DidaManager.Native;
using System.Runtime.InteropServices;

namespace DidaManager
{
    public partial class MainForm : Form
    {
        private ChromiumWebBrowser? chromeBrowser = null;
        private static ContextMenuHandler? mHandler = null;
        private FullMultiDbServer? cefSharpServer = null;
        private CefSharpNative? cefSharpNative = null;
        private bool m_bShowConsole = false;

        [DllImport("kernel32.dll")]
        private static extern bool AllocConsole();

        [DllImport("kernel32.dll")]
        private static extern bool FreeConsole();

        public MainForm()
        {
            InitializeComponent();

            // 设置窗体最大化显示
            this.WindowState = FormWindowState.Maximized;

            LogManager.Info("主窗体初始化开始");

            mHandler = new ContextMenuHandler(this);

            // 设置窗体图标
            try
            {
                string iconPath = Path.Combine(Application.StartupPath, "res", "logo.ico");
                if (File.Exists(iconPath))
                {
                    this.Icon = new Icon(iconPath);
                    LogManager.Debug($"设置窗体图标: {iconPath}");
                }
                else
                {
                    LogManager.Warn($"图标文件不存在: {iconPath}");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error("设置图标失败", ex);
            }

            try
            {
                string debugFlagPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "debug.flag");
                if (File.Exists(debugFlagPath))
                {
                    AllocConsole();// 程序启动时创建控制台
                    m_bShowConsole = true;
                }
#if USE_LOCAL_HTML
                // 1、在启动前需要判断一下update目录是否存在
                // 2、如果存在需要res/html下的文件删除
                // 3、把update目录下的文件拷贝到res/html目录下
                string updateTempDir = Path.Combine(Application.StartupPath, "update_temp");
                string updateDir = Path.Combine(Application.StartupPath, "update");
                if (Directory.Exists(updateDir))
                {
                    // 删除res/html下的文件
                    string htmlDir = Path.Combine(Application.StartupPath, "res", "html");
                    if (Directory.Exists(htmlDir))
                    {
                        Directory.Delete(htmlDir, true);
                    }
                    // 把update目录下的文件拷贝到res/html目录下
                    Directory.Move(updateDir, htmlDir);
                    LogManager.Info($"把update目录下的文件拷贝到res/html目录下: {updateDir} -> {htmlDir}");
                    if (Directory.Exists(updateTempDir))
                    {
                        Directory.Delete(updateTempDir, true);
                    }
                }
#endif
                LogManager.Info("初始化 CefSharp 浏览器");
                // 需要区分是加载本地html还是使用http://localhost:8080/，本地文件是放在res/html/index.html
                string page = "http://localhost:8080/";
#if USE_LOCAL_HTML
                // 获取当前目录
                string? currentPath = Path.GetDirectoryName(Application.ExecutablePath);
                string? htmlPath = Path.Combine(currentPath??"", "res", "html", "index.html");
                if (File.Exists(htmlPath))
                {
                    page = htmlPath;
                }
#else
                page = "http://localhost:8080/";
#endif

                // 创建浏览器组件
                chromeBrowser = new ChromiumWebBrowser(page);

                // 创建 CefSharpBridge 实例,需要传数据库路径
                cefSharpServer = new FullMultiDbServer();

                // 创建 CefSharpNative ,调用本地接口
                cefSharpNative = new CefSharpNative(this);

                // 添加到窗体并填充
                this.panel_Main.Controls.Add(chromeBrowser);
                chromeBrowser.Dock = DockStyle.Fill;
                chromeBrowser.BringToFront();
                // 设置浏览器选项
                var browserSettings = new BrowserSettings
                {
                    LocalStorage = CefState.Enabled,
                    // 改善缩放和渲染质量
                    WebGl = CefState.Enabled,
                    //AcceleratedCompositing = CefState.Enabled,
                    WindowlessFrameRate = 60, // 提高帧率
                };

                chromeBrowser.BrowserSettings = browserSettings;
                chromeBrowser.MenuHandler = mHandler;
                LogManager.Info($"浏览器初始化完成，加载页面: {page}");
            }
            catch (Exception ex)
            {
                LogManager.Error("初始化浏览器时出错", ex);
                MessageBox.Show($"初始化浏览器时出错：{ex.Message}\n{ex.StackTrace}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            LogManager.Info("主窗体初始化完成");
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (chromeBrowser != null)
            {
                chromeBrowser.JavascriptObjectRepository.Register("cefSharpServer", cefSharpServer, BindingOptions.DefaultBinder);
                chromeBrowser.JavascriptObjectRepository.Register("cefSharpNative", cefSharpNative, BindingOptions.DefaultBinder);
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            try
            {
                LogManager.Info("开始关闭主窗体");
                
                // 释放 CefSharp 资源
                if (chromeBrowser != null)
                {
                    chromeBrowser.Dispose();
                    chromeBrowser = null;
                    LogManager.Debug("CefSharp 浏览器资源已释放");
                }

                if (m_bShowConsole)
                {
                    FreeConsole();
                }
                Cef.Shutdown();
                LogManager.Info("CefSharp 已关闭");
            }
            catch (Exception ex)
            {
                LogManager.Error("关闭浏览器时出错", ex);
                MessageBox.Show($"关闭浏览器时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            base.OnFormClosing(e);
        }

        public void RefreshPage()
        {
            if (chromeBrowser != null)
            {
                // 需要区分是加载本地html还是使用http://localhost:8080/，本地文件是放在res/html/index.html
                string page = "http://localhost:8080/";
#if USE_LOCAL_HTML
                // 获取当前目录
                string? currentPath = Path.GetDirectoryName(Application.ExecutablePath);
                string? htmlPath = Path.Combine(currentPath ?? "", "res", "html", "index.html");
                if (File.Exists(htmlPath))
                {
                    page = htmlPath;
                }
#else
                page = "http://localhost:8080/";
#endif
                chromeBrowser.Load(page);
            }
        }
        public void InvokeOnParent(Action action)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(action);
            }
            else
            {
                action();
            }
        }

    }

}
